package com.xing.controller;

import com.xing.entity.Student;
import com.xing.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/index")
public class IndexHandler {

    @GetMapping("/index")
    public String index(Model model){
        System.out.println("index....");

        List<Student> list=new ArrayList<>();
        list.add(new Student(1L,"幸福哈",22));
        list.add(new Student(20L,"张三",23));
        list.add(new Student(3L,"李四",24));

        model.addAttribute("list",list);
        return "/index";
    }

    @GetMapping("/index2")
    public String index2(Map<String,String> map){
        map.put("name","张三");
        return "index2";
    }

    @GetMapping("/if")
    public String index3(Map<String,Boolean> map){
        map.put("flag",true);
        return "index";
    }

    @GetMapping("/test1")
    public String test(Model model){
        model.addAttribute("name","tom");
        return "test1";
    }

    @GetMapping("/url/{nam}")
    @ResponseBody //把数值直接传递给客户端
    public String url(@PathVariable("nam") String name){
        return name;
    }

    @GetMapping("/request")
    public String object(HttpServletRequest request){
        request.setAttribute("request","request对象");
        request.getSession().setAttribute("session","session对象");
        return "test1";
    }

    @GetMapping("/util")
    public String util(Model model ){
        model.addAttribute("name","张三");
        model.addAttribute("users",new ArrayList<>());
        model.addAttribute("count",22);
        model.addAttribute("date",new Date());

        return "test1";
    }

    /*BindingResult是用于接收前一个参数校验(validate或valid)错误信息,
    前端将不再显示错误信息statusCode == 200, 后端也不会抛出异常*/
    @GetMapping("/validator")
     public void validatorUser(@Valid User user, BindingResult bindingResult){
        System.out.println(user);
        if (bindingResult.hasErrors()){
            List<ObjectError> list = bindingResult.getAllErrors();
            for (ObjectError objectError : list) {
                System.out.println(objectError.getCode()+"-"+objectError.getDefaultMessage());
            }
        }
     }




}
